package com.gaga.crm;

import com.gaga.crm.pojo.SysUser;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.*;
import org.springframework.test.context.junit4.SpringRunner;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

@SpringBootTest
@RunWith(SpringRunner.class)
public class RedisTemplateTester {

    @Resource
    private StringRedisTemplate stringRedisTemplate; //操作字符串数据

    @Resource
    private RedisTemplate redisTemplate; //操作其他数据类型

    //操作字符串
    @Test
    public void testString() {
        stringRedisTemplate.opsForValue().set("name", "嘎嘎");
        Assert.assertEquals("嘎嘎", stringRedisTemplate.opsForValue().get("name"));
    }

    //操作实体
    @Test
    public void testObj() {
        SysUser user = new SysUser("操作实体嘎嘎", "123456", 1, null);
        ValueOperations<String, SysUser> operations = redisTemplate.opsForValue();
        operations.set("crm.user.gaga", user);  //插入实体数据
        SysUser u = operations.get("crm.user.gaga");    //获取实体数据
        System.out.println("user.usrName: " + u.getUsrName());
    }

    //超时失效
    @Test
    public void testExpire() throws InterruptedException {
        SysUser user = new SysUser("操作实体嘎嘎", "123456", 1, null);
        ValueOperations<String, SysUser> operations = redisTemplate.opsForValue();
        operations.set("expire", user, 100, TimeUnit.MILLISECONDS);
        Thread.sleep(1000);
        boolean exists = redisTemplate.hasKey("expire");
        if (exists) {
            System.out.println("exists is true");
        } else {
            System.out.println("exists is false");
        }
    }

    //操作哈希
    @Test
    public void testHash() {
        HashOperations<String, Object, Object> hash = redisTemplate.opsForHash();
        hash.put("hash", "name", "gaga嘎嘎");
        String value = (String) hash.get("hash", "name");
        System.out.println("hash name'value :" + value);
    }

    //操作列表
    @Test
    public void testList() {
        ListOperations<String, String> list = redisTemplate.opsForList();
        list.leftPush("list", "mama");
        list.leftPush("list", "cs");
        list.leftPush("list", "gg");
        String value = (String) list.leftPop("list");
        System.out.println("list value :" + value.toString());
    }

}
